/// <reference path="../Scripts/jquery-1.7.1.min.js" />
/// <reference path="../Scripts/knockout-2.1.0.js" />

function UserProfileViewModel() {
    var self = this;
    // put a property loop here
    self.UserId = ko.observable();
    self.UserName = ko.observable();
    self.TS = ko.observable();
    self.CreatedBy = ko.observable();
    self.CreatedDt = ko.observable();
    self.ModifiedBy = ko.observable();
    self.ModifiedDt = ko.observable();
    self.IsActive = ko.observable();
    self.FirstName = ko.observable();
    self.LastName = ko.observable();
    self.Address = ko.observable();
    self.City = ko.observable();
    self.Region = ko.observable();
    self.PostalCode = ko.observable();
    self.OfficePhone = ko.observable();
    self.CellPhone = ko.observable();
    self.Title = ko.observable();
    self.Action = ko.observable();
    self.Caller = ko.observable();
    self.Role = ko.observable();
    self.PageSize = ko.observable();
    self.PageNumber = ko.observable();
    self.SortColumn = ko.observable();
    self.SortType = ko.observable();
    self.TotalRows = ko.observable();

    self.Password = ko.observable();
    self.ConfirmPassword = ko.observable();
    self.PasswordQuestion = ko.observable();
    self.PasswordAnswer = ko.observable();
    self.Email = ko.observable();
    self.auserid = ko.observableArray();
    self.AddingUser = ko.observable();
    self.LoadingUserprofile = ko.observable();
    self.EditingUser = ko.observable();

    self.selectedVal = ko.observableArray([]);
    self.UserProfileList = ko.observableArray([]);


    self.setUserProfile = function (
			UserId, UserName, TS, CreatedBy, CreatedDt, ModifiedBy, ModifiedDt, IsActive, FirstName, LastName, Address, City, Region, PostalCode, OfficePhone, CellPhone, Title, _Action, _Caller, _Role, _PageNumber, _PageSize, _SortColumn, _SortType, _TotalRows

	) {

        UserId = _UserId;
        UserName = _UserName;
        TS = _TS;
        CreatedBy = _CreatedBy;
        CreatedDt = _CreatedDt;
        ModifiedBy = _ModifiedBy;
        ModifiedDt = _ModifiedDt;
        IsActive = _IsActive;
        FirstName = _FirstName;
        LastName = _LastName;
        Address = _Address;
        City = _City;
        Region = _Region;
        PostalCode = _PostalCode;
        OfficePhone = _OfficePhone;
        CellPhone = _CellPhone;
        Title = _Title;
        Action = _Action;
        Caller = _Caller;
        Role = _Role;
        PageSize = _PageSize
        PageNumber = _PageNumber;
        SortColumn = _SortColumn;
        SortType = _SortType;
        TotalRows = _TotalRows;

    }; //  End of set procedure 

    self.passQS = ko.observableArray([]);

    function userItem(id, dic) {
        this.PasswordQuestionID = ko.observable(id);
        this.PasswordQuestionDesc = ko.observable(dic);

    }
    //select available  users 
    self.availablePasswordQuestion = function () {
        var self = this;
        this.Action = "GetAll";
        this.Caller = "trooks";
        this.Role = "user";

        jQuery.ajax({
            url: "./api/PasswordQuestionAPI/",
            type: 'get',
            data: { Action: self.Action, Caller: self.Caller, Role: self.Role, PageNumber: self.PageNumber, PageSize: self.PageSize, SortColumn: self.SortColumn, SortType: self.SortType },
        }).done(function (data) {


            self.auserid.removeAll();
            $.each(data, function (key, val) {
                self.auserid.push(new userItem(val.PasswordQuestionID, val.PasswordQuestionDesc));
            })
        });



    };

    function passItem(id, dis) {
        this.PasswordQuestionID = ko.observable(id);
        this.PasswordQuestionDesc = ko.observable(dis);

    }

    self.AddUser = function (appVal2) {
        self.availablePasswordQuestion(appVal2);      
        self.AddingUser(appVal2);
    };

    //Add User Profile
    self.AddUserProfile = function () {
        var self = this;
        this.Action = "Add";
        this.Caller = "trooks";
        this.Role = "user";

        $(".addform").validate({
           
        });
        if (!$(".addform").valid()) {
            return;
        }

        jQuery.ajax({
            url: "./Account/Register/",
            type: 'post',           
            data: ko.toJSON({ Action: self.Action, Caller: self.Caller, UserName: self.UserName, FirstName: self.FirstName, LastName: self.LastName, Address: self.Address, City: self.City, Region: self.Region, PostalCode: self.PostalCode, OfficePhone: self.OfficePhone, CellPhone: self.CellPhone, Title: self.Title, Password: self.Password, ConfirmPassword: self.ConfirmPassword, PasswordQuestion: self.selectedVal().PasswordQuestionID, PasswordAnswer: self.PasswordAnswer, Email: self.Email }),
            contentType: 'application/json',
            success: function (result) {
                $('#myModaladd2').modal('hide');
                self.GetUserProfileByParameter();
            },
            error: function (xhr, ajaxOptions, thrownError) {
                $('#error-dis').text(thrownError);
                $('#register-error').css({ 'display': 'block' });
                $('#SearchFilter-home').css({ 'display': 'none' });
                $('#myModaladd2').modal('hide');
                $(document).scrollTop(0);
            }


        });
        $(".addform")[0].reset();
    }; //End of add procedure   
    self.LoadUserprofile = function (appVal) {
        self.LoadingUserprofile(appVal);       
    };

    //Delete User Profile
    self.DeleteUserprofile = function (appval) {
     
        self.Action = "RemoveUserAccount";
        self.Caller = "trooks";
        self.Role = "user";
       
        jQuery.ajax({
            url: "./Account/RemoveUserAccount/",
            type: 'post',         
            data: ko.toJSON({ UserName: appval.UserName }),
            contentType: 'application/json',
            success: function (result) {
                $('#myModel').modal('hide');
                self.GetUserProfileByParameter();
                //alert(result);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                $('#myModel').modal('hide');
                $('#error-dis').text(thrownError);
                $('#register-error').css({ 'display': 'block' });
                $('#SearchFilter-home').css({ 'display': 'none' });
                $(document).scrollTop(0);
            }
        });     
    };

    //Edit User Profile
    self.EditUser = function (appVal2) {
        self.EditingUser(appVal2);
    };

  



    self.UpdateUserprofile = function (appval) {
        self.Action = "Update";
        self.Caller = "trooks";
        self.Role = "user";

        $(".editform").validate({
            rules: {
                txtUserName: { required: true }, txtFirstName: { required: true }, txtLastName: { required: true }, txtAddress: { required: true }, txtCity: { required: true }
            , txtRegion: { required: true }, txtPostalCode: { required: true }, txtOfficePhone: { required: true }, txtCellPhone: { required: true }, txtTitle: { required: true }
            }
        });
        if (!$(".editform").valid()) {
            return;
        }
        jQuery.ajax({
            url: "./api/UserProfileapi/",           
            data: ko.toJSON({
                UserId: appval.UserId, Action: self.Action, Caller: self.Caller, UserName: appval.UserName,
                FirstName: appval.FirstName, LastName: appval.LastName, Address: appval.Address,
                City: appval.City, Region: appval.Region, PostalCode: appval.PostalCode, OfficePhone: appval.OfficePhone,
                CellPhone: appval.CellPhone, Title: appval.Title, TS: appval.TS, Password: appval.Password, IsActive: appval.IsActive,
                CreatedBy: appval.CreatedBy, CreatedDt: appval.CreatedDt, ModifiedBy: appval.ModifiedBy, ModifiedDt: appval.ModifiedDt
            }),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                $('#editmodel').modal('hide');
                self.GetUserProfileByParameter();
               
            },
            error: function (xhr, ajaxOptions, thrownError) {
                $('#error-dis').text(thrownError);
                $('#register-error').css({ 'display': 'block' });
                $('#SearchFilter-home').css({ 'display': 'none' });
                $(document).scrollTop(0);
                $('#editmodel').modal('hide');
            }
        });
    };

    //loading model popup
    ko.bindingHandlers['modal'] = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var allBindings = allBindingsAccessor();
            var $element = $(element);
            $element.addClass('hide modal');

            if (allBindings.modalOptions) {
                if (allBindings.modalOptions.beforeClose) {
                    $element.on('hide', function () {
                        return allBindings.modalOptions.beforeClose();
                    });
                }
            }

            return ko.bindingHandlers['with'].init.apply(this, arguments);
        },
        update: function (element, valueAccessor) {
            var value = ko.utils.unwrapObservable(valueAccessor());

            var returnValue = ko.bindingHandlers['with'].update.apply(this, arguments);

            if (value) {
                $(element).modal('show');
            } else {
                $(element).modal('hide');
            }

            return returnValue;
        }
    };


    //Sort user profile
    self.sortRecords = ko.observableArray();

    ko.bindingHandlers.sort = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var asc = false;
            element.style.cursor = 'pointer';

            element.onclick = function () {
                var value = valueAccessor();
                var prop = value.prop;
                var data = value.arr;

                asc = !asc;
                if (asc) {
                    self.UserProfileList.sort(function (left, right) {
                        return left[prop] == right[prop] ? 0 : left[prop] < right[prop] ? -1 : 1;
                    });
                } else {
                    self.UserProfileList.sort(function (left, right) {
                        return left[prop] == right[prop] ? 0 : left[prop] > right[prop] ? -1 : 1;
                    });
                }
            }
        }
    };

    //filter user
    self.filter = ko.observable("");
    
    self.filteredUser = ko.computed(function () {
        var filterText = self.filter().toLowerCase();
        return ko.utils.arrayFilter(self.UserProfileList(), function (item) {
            return filterText.length < 1 || item.UserId == filterText || item.UserName.toLowerCase().indexOf(filterText) != -1
        });

    }, self);



    self.GetUserProfileByParameter = function () {                   
        this.Action = "GetAll";
        this.Caller = "trooks";
        this.Role = "user";
        this.PageNumber = 1;
        this.PageSize = 10;
        this.SortColumn = "UserId";
        this.SortType = "asc";
        
        jQuery.ajax({
            url: "./api/UserProfileapi/",
            type: 'get',
            data: { Action: self.Action, Caller: self.Caller, Role: self.Role, PageNumber: self.PageNumber, PageSize: self.PageSize, SortColumn: self.SortColumn, SortType: self.SortType, FullName: self.FullName },

            success: function (result) {
                self.UserProfileList.removeAll();
                $.each(result, function (key, val) {
                    self.UserProfileList.push(
                        val
                    )
                })
            },
            error: function (xhr, ajaxOptions, thrownError) {
                $('#error-dis').text(thrownError);
                $('#register-error').css({ 'display': 'block' });
                $('#SearchFilter-home').css({ 'display': 'none' });                
                $(document).scrollTop(0);
            }
       
        });
        if (loginUserRole.indexOf('user') > -1) {
            $('.add-btn').attr('disabled', 'disabled');
        }             
    };

    ko.bindingHandlers.bootstrapPopover = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            var options = valueAccessor();
            var defaultOptions = { trigger: 'hover' };
            options = $.extend(true, {}, defaultOptions, options);
            $(element).popover(options);
        }
    };

   
   


}; //End of view model





